import { Injectable } from '@angular/core';
import {webSocket} from "rxjs/webSocket";
import {WebSocketMessage, WebSocketSubject} from "rxjs/internal/observable/dom/WebSocketSubject";
import {catchError, connect, EMPTY, Observable, Subject, switchAll, tap} from "rxjs";
import {Message} from "../model/Message";



@Injectable({
  providedIn: 'root'
})
export class CallcenterService {

  private socket$: WebSocketSubject<any>;
  private messagesSubject$ = new Subject();
  WS_ENDPOINT ="ws://192.168.2.66:2066/callcenter";
  public messages$ = this.messagesSubject$;


  constructor() {

  }





  public async connect(): Promise<boolean> {

    try {
      if (!this.socket$ || this.socket$.closed) {

         await this.getNewWebSocket()
          .then((data:any)=>{

            this.socket$=data;
            this.socket$.subscribe(
              this.messagesSubject$

            )
          })

        // console.dir(this.socket$);
        //   this.socket$.next('Hellow')
        //在这里发送身份认证

        // const messages = this.socket$.pipe(
        //   tap({
        //     error: error => console.log(error),
        //   }), catchError(_ => EMPTY));
        // this.messagesSubject$.next(messages);

      }
      else {
        this.socket$.subscribe(
          this.messagesSubject$
        )
      }
      return true;
    } catch (e) {
      return false;
    }




  }
  private async getNewWebSocket() :Promise<WebSocketSubject<any>>{
    //console.log('条件触发');
    return webSocket({url:this.WS_ENDPOINT,
          deserializer:({data})=>{
      let m=new Message();
     // console.log(data);
      m=JSON.parse(data)
      return m;
          }

    });
  }

  sendMessage(msg: any) {
    this.socket$.next(msg);
  }

  close() {
    this.socket$.complete();

    this.messagesSubject$.unsubscribe();
    this.socket$.unsubscribe();
  }








}
